package com.yyx.oneselfnetty.common;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Date;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //1.创建事件循环组
        DefaultEventLoopGroup group = new DefaultEventLoopGroup(2);
        System.out.println(group.next());
        System.out.println(group.next());
        System.out.println(group.next());




        new Bootstrap() //启动类
                .group(new NioEventLoopGroup())  //添加NioEventLoopGroup
                .channel(NioSocketChannel.class) //选择客户端Channel实现
                .handler(new ChannelInitializer<NioSocketChannel>() { //添加处理类
                    //在链接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                }).connect("127.0.0.1",8080) //连接服务器
                .sync()  //阻塞方法，直到连接建立
                .channel()  //代表连接对象
                .writeAndFlush(new Date() + "Hello World!");  //发送数据

                //把发送的数据转化为ByteBuf
                //由某个EventLoop处理read操作(accept\read)，接受到bytebuf
                //将bytebuf还原为String
                //执行read方法，打印hello
    }
}
